<?php
namespace Admin\Model;
use Think\Model;

class SmtpModel extends Model{
	//自动验证
	protected $_validate = array(
		array('smtp','1,20','SMTP服务器不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('port','/^\d{1,6}$/','SMTP端口必须是数字，且不得大于6位！',self::EXISTS_VALIDATE),
		array('email','email','发信人邮件地址必须为邮箱格式！',self::EXISTS_VALIDATE),
		array('user','email','SMTP身份验证用户名必须为邮箱格式！',self::EXISTS_VALIDATE),
		array('pass','1,50','SMTP身份验证密码不得为空或大于50位！',self::EXISTS_VALIDATE,'length'),
	);
	
	//查询总记录
	public function total(){
		return $this->where($this->map())->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('id,smtp,port,email,user')
					->where($this->map())
					->order(array('id'=>'DESC'))
					->limit($firstRow,C('PAGE_SIZE'))
					->select();
	}
	
	//查询一条
	public function one(){
		$map['id'] = I('get.id');
		return $this->field('smtp,port,email,user')->where($map)->find();
	}
	
	//查询运行中的服务器
	public function one2(){
		$firstRow = date('H') % $this->total();
		return $this->field('smtp,port,email,user,pass')->order(array('id'=>'DESC'))->limit($firstRow,1)->select();
	}
	
	//查询运行中的服务器
	public function one3($hour){
		$firstRow = $hour % $this->total();
		return $this->field('id,smtp,port,email,user')->order(array('id'=>'DESC'))->limit($firstRow,1)->select();
	}
	
	//添加
	public function insert(){
		$data = array(
			'smtp'=>I('post.smtp'),
			'port'=>I('post.port'),
			'email'=>I('post.email'),
			'user'=>I('post.user'),
			'pass'=>I('post.pass')
		);
		if ($this->create($data)){
			$id = $this->add();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//修改
	public function update(){
		$data = array(
			'id'=>I('get.id'),
			'smtp'=>I('post.smtp'),
			'port'=>I('post.port'),
			'email'=>I('post.email'),
			'user'=>I('post.user')
		);
		if (I('post.pass')) $data['pass'] = I('post.pass');
		if ($this->create($data)){
			$id = $this->save();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//删除
	public function remove(){
		$affected_rows = $this->delete(I('get.id'));
		if ($affected_rows) $this->execute('OPTIMIZE TABLE `__PREFIX__smtp`');
		return $affected_rows;
	}
	
	//搜索
	private function map(){
		$map = array(
			'_complex'=>array(
				'smtp'=>array('like','%'.I('get.keyword').'%'),
				'port'=>array('like','%'.I('get.keyword').'%'),
				'email'=>array('like','%'.I('get.keyword').'%'),
				'user'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			)
		);
		return $map;
	}
}